package com.ityuwen.mengyagushi.user.login;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginClient implements ApplicationContextAware {

    private static final Map<String, ILogin> map = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取注解所在的bean
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(BeanType.class);
        // 判断是否为空
        if (CollectionUtils.isEmpty(beanMap)){
            return;
        }
        // 获取bean列表
        Collection<Object> beans = beanMap.values();
        if (CollectionUtils.isEmpty(beanMap)){
            return;
        }
        // 遍历bean集合放入map
        beans.forEach(bean -> {
            BeanType annotation = bean.getClass().getAnnotation(BeanType.class);
            map.put(annotation.value().type, (ILogin)bean);
        });
    }

    public Map<String, Object> login(String type, Map<String, Object> parameterMap){
        return map.get(type).login(parameterMap);
    }
}
